<template>
    <div class="recent_contact">
        <lemon-imui :user="user" ref="IMUI" width="100%" height="100vh" hideMenu :sendText="$t('msg.发送')"
            :contextmenu="contextmenu" :contact-contextmenu="contactContextmenu"
            :hide-message-time="setting.hideMessageTime" :sendKey="setSendKey" :wrapKey="wrapKey"
            :latelyContacts="latelyContacts" @is-bottom="eventBottom" @change-contact="handleChangeContact"
            @pull-messages="handlePullMessages" @message-click="handleMessageClick" @send="handleSend"
            style="min-height:600px">
            <template #cover>
                <div class="cover">
                    <i class="lemon-icon-message"></i>
                    <p><b>mmm即时通讯</b></p>
                </div>
            </template>
            <!-- 左侧---最近联系人列表插槽 -->
            <template #sidebar-message="Contact">
                <div class="contact_item" :class="Contact.is_top == 1 ? 'bg-gray' : ''">
                    <el-badge :value="Contact.unread" :max="99" :is-dot="Contact.is_notice == 0"
                        :hidden="Contact.unread <= 0" class="contact_badge">
                        <div class="contact_avatar" v-bind:class="{ 'lemon-avatar--circle': setting.avatarCricle }">
                            <img :src="Contact.avatar" />
                        </div>
                        <span class="is_online"
                            v-if="Contact.is_online && Contact.is_group == 0 && globalConfig.chatInfo.online == 1"
                            title="在线"></span>
                    </el-badge>

                    <div class="contact_info">
                        <div class="contact_other">
                            <div class="name">{{ Contact.displayName }}</div>
                            <div class="time">{{ formatTime(Contact.lastSendTime) }}</div>
                        </div>
                        <div class="lemon-contact__content last_msg">
                            <div class="last_msg_view">
                                <span v-html="Contact.lastContent" class="last_msg_span"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 左2---最近联系人列表顶部插槽 不滚动-->
            <template #sidebar-message-fixedtop="instance">
                <div class="lz-flex no-internet pd-10 mb-10 lz-space-between lz-align-items-center" v-if="!wsStatus">
                    <div class="el-icon-info"></div>
                    <div>{{ $t('msg.无法接收消息') }}</div>
                    <div class="el-icon-refresh cur-handle" @click="reconnect"></div>
                </div>

                <div class="contact-fixedtop-box">
                    <el-input :placeholder="$t('msg.搜索联系人')" prefix-icon="el-icon-search" v-model="keywords"
                        @focus="searchResult = true" @blur="closeSearch" class="input-with-select">
                    </el-input>

                    <div style="margin-left:18px">
                        <el-dropdown @command="handleCommand">
                            <el-button icon="el-icon-plus" circle></el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="addGroup" v-if="globalConfig.chatInfo.groupChat">
                                    <div class="dropdown_item">
                                        <img src="@/assets/image/chat.png" alt="">
                                        <span>{{ $t('msg.发起群聊') }}</span>
                                    </div>
                                </el-dropdown-item>

                                <el-dropdown-item command="addFriend">
                                    <div class="dropdown_item">
                                        <img src="@/assets/image/add.png" alt="">
                                        <span>{{ $t('msg.添加朋友') }}</span>
                                    </div>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="search-list" v-show="searchResult">
                        <div v-if="searchList.length">
                            <div v-for="(item, index) in searchList" :key="index" class="search-list-item">
                                <lemon-contact :contact="item" @click="openChat(item.id, instance)" />
                            </div>
                        </div>
                        <div v-if="searchList.length == 0" style="margin: 20px" align="center">
                            {{ $t('暂无数据') }}
                        </div>
                    </div>
                </div>
            </template>


            <!-- 中间---消息窗口顶部的插槽 -->
            <template #message-title="contact">
                <div class="message-title-box">
                    <div>
                        <span class="displayName" v-if="is_group == 0">
                            <OnlineStatus :type="contact.is_online ? 'success' : 'info'" :pulse="contact.is_online"
                                v-if="globalConfig.chatInfo.online"></OnlineStatus>
                            {{ contact.displayName }}
                        </span>

                        <span class="displayName" v-if="is_group == 1">
                            {{ group_name }}
                            <span class="mr-5">({{ groupUserCount }})</span>
                        </span>
                    </div>
                    <div class="message-title-tools">
                        <i class="el-icon-more ml-10" @click="rightShow = !rightShow"></i>
                    </div>

                    <div class="message_warning" v-if="isTempMsg">
                        <div class="message_warning_content">
                            <img src="@/assets/image/warning.png" alt="">
                            <span>{{ $t('msg.当前为临时会话窗口') }}</span>
                            <div class="message_warning_close" @click="isTempMsg = false">
                                <img src="@/assets/image/w_close.png" alt="">
                            </div>
                        </div>
                    </div>
                </div>
            </template>
            <!-- 右侧--- -->
            <template #message-side="contact" v-if="rightShow">
                <!-- 群组聊天展示的抽屉 -->
                <div class="slot-group-list lemon-wrapper" v-if="contact.is_group == 1">
                    <div class="group_content">
                        <el-input :placeholder="$t('msg.搜索')" prefix-icon="el-icon-search" v-model="searchGroupUserName"
                            class="group_search" @keyup.enter.native="searchGroupUser" />
                        <div class="group_user_list">
                            <lemon-contact :contact="item" v-for="(item, index) in groupUserList"
                                :key="`popover_${index}`" v-lemon-contextmenu.contact="groupMenu">


                                <el-popover placement="left" class="group_user_item">
                                    <div class="popover_content">
                                        <div class="popover_content_view">
                                            <img :src="item.userInfo.avatar" alt="" class="popover_avatar">
                                            <div class="popover_info">
                                                <div class="popover_name">{{ item.userInfo.displayName }}</div>
                                                <div class="popover_id">ID:{{ item.userInfo.id }}</div>
                                            </div>
                                        </div>

                                        <div class="popover_btn" v-if="item.user_id != user_mmm.im_user_id">
                                            <div class="popover_btn_item" @click="add_friend(item)">
                                                {{ $t('msg.添加朋友') }}
                                            </div>
                                            <div class="popover_btn_item" @click="send_msg(item)">
                                                {{ $t('msg.发消息') }}
                                            </div>
                                        </div>
                                    </div>

                                    <div class="group_user_item_info" slot="reference">
                                        <img :src="item.userInfo.avatar" alt="" class="group_user_avatar">
                                        <div class="group_user_name">{{ item.userInfo.displayName }}</div>
                                    </div>
                                </el-popover>
                            </lemon-contact>

                            <div class="group_user_item" @click="openAddGroupUser">
                                <img src="@/assets/image/g_a.png" alt="" class="group_user_avatar">
                            </div>
                        </div>

                        <div class="group_more" @click="showMoreGroupUsers" v-if="groupUserCount > show_max_count">
                            <span class="key">{{ is_expand ? $t('msg.收起') : $t('msg.更多群成员') }}</span>
                            <img src="@/assets/image/more.png" alt="">
                        </div>

                        <div class="group_bottom">
                            <div class="group_setup">
                                <div class="group_setup_item" @click="changeGroupName('editGroupName')">
                                    <!-- {{ $t('msg.群聊名称') }}  -->
                                    <div class="group_setup_key">{{ group_name }}</div>
                                    <div class="group_setup_value">{{ $t('msg.修改后将在群内通知') }}</div>
                                </div>
                                <div class="group_setup_item" @click="changeGroupName('groupQrCode')">
                                    <div class="group_setup_key">{{ $t('msg.群二维码') }}</div>
                                    <div class="group_setup_value">{{ $t('msg.点击查看群聊二维码') }}</div>
                                </div>
                                <div class="group_setup_item" @click="changeGroupName('editGroupNickname')">
                                    <div class="group_setup_key">{{ $t('msg.我在本群的昵称') }}</div>
                                    <div class="group_setup_value">{{ groupUserName }}</div>
                                </div>
                            </div>
                            <div class="group_clear_msg" @click="clearGroupMsg">{{ $t('chat.清空聊天记录') }}</div>


                            <div class="group_out" @click="removeGroup" v-if="isGroupAdmin">{{ $t('msg.解散群组') }}
                            </div>
                            <div class="group_out" @click="removeUser" v-else>{{ $t('msg.退出群聊') }}</div>
                        </div>
                    </div>
                </div>
                <!-- 个人聊天展示的抽屉 -->
                <div class="slot-group-list lemon-wrapper" v-else>
                    <div class="group_user">
                        <div class="group_user_info" v-popover:popover>
                            <img :src="currentChat.avatar" alt="" class="group_user_avatar">
                            <div class="group_user_other">
                                <div class="group_user_name">{{ currentChat.displayName }}</div>
                                <div class="group_user_id">ID：{{ currentChat.id }}</div>
                            </div>

                            <el-popover placement="left" ref="popover" v-model="popover_show">
                                <FriendInfo type="index" :im_id="currentChat.id" @close="closeFriendInfo" />
                            </el-popover>
                        </div>
                        <div class="group_msg_item" @click="messageBox = true">
                            <div>{{ $t('chat.查找聊天记录') }}</div>
                            <img src="@/assets/image/r.png" alt="">
                        </div>
                    </div>
                </div>
            </template>
            <!-- 每条消息后面展示的文字 -->
            <template #message-after="message">
                <span v-if="message.fromUser.id == user.id && message.is_group == 0" style="visibility: visible">
                    <span v-if="!message.is_read && message.status == 'succeed'"> {{ $t('chat.未读') }} </span>
                    <span v-if="message.is_read && message.status == 'succeed'" class="fc-success">
                        {{ $t('chat.已读') }}
                    </span>
                </span>
            </template>
            <!-- 中间底部---发送按钮左边插槽 -->
            <template #editor-footer>
                <div class="lz-flex lz-space-between lz-align-items-center">
                    <div></div>
                    <div>{{ setting.sendKey == 1 ? $t('chat.换行') : $t('chat.发送消息') }}</div>
                    <!-- <div>{{ setting.sendKey == 1 ? '使用 Ctrl + Enter 换行' : '使用 Ctrl + Enter 发送消息' }}</div> -->
                </div>
            </template>
        </lemon-imui>


        <!-- 左2搜索框右侧+号的回调 -->
        <!-- 创建群聊 -->
        <Group :visible.sync="createChatBox" :title="dialogTitle" @manageGroup="manageGroup" :isAdd="isAdd"
            :userIds="userIds" :groupId="group_id" />
        <!-- 添加朋友 -->
        <FriendAdd :visible.sync="friendAddBox" @ok="add_send_msg" />
        <!-- 添加好友申请框 -->
        <AddFriend :member="member" :visible.sync="addFriendBox" />



        <!-- 红包弹窗和群聊弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogBoolen" :modal="true" :center="true" width="426px"
            :show-close="false" append-to-body destroy-on-close>
            <Transfer :member="currentChat" v-if="dialogName == 'transfer'" @ok="transfer_ok" />
            <TransferResult :id="transfer_id" v-else-if="dialogName == 'result'" @ok="dialogBoolen = false" />
            <TransferFail :id="transfer_id" v-else-if="dialogName == 'fail'" @ok="dialogBoolen = false" />
            <TransferPeding :id="transfer_id" v-else-if="dialogName == 'peding'" @ok="peding_ok" />
            <TransferSuccess :id="transfer_id" v-else-if="dialogName == 'success'" />

            <editGroupName :id="group_id" :remarkName="group_name" v-else-if="dialogName == 'editGroupName'"
                @ok="changeCallback" @close="dialogBoolen = false" />
            <editGroupNickname :id="group_id" :remarkName="groupUserName" v-else-if="dialogName == 'editGroupNickname'"
                @ok="changeCallback" @close="dialogBoolen = false" />

            <groupQrCode :id="group_id" v-else-if="dialogName == 'groupQrCode'" @close="dialogBoolen = false" />
        </el-dialog>

        <!-- 历史聊天信息-消息管理器 -->
        <el-dialog :title="$t('msg.历史消息')" :visible.sync="messageBox" :modal="true" width="800px" append-to-body>
            <ChatRecord :contact="currentChat" :condition="ChatRecordMap" :key="componentKey"></ChatRecord>
        </el-dialog>
        <Socket ref="socket"></Socket>
    </div>
</template>

<script>
import { mapState } from "vuex";

import EmojiData from "@/utils/emoji";
import * as utils from "@/utils/index";
import Lockr from "lockr";

import OnlineStatus from "@/components/message/mini/statusIndicator";
import Socket from "@/components/message/socket";
import ChatRecord from "@/components/message/chatRecord";

import Group from "@/components/message/group/index";
import FriendAdd from "@/components/message/user/FriendAdd";
import AddFriend from "@/components/message/user/AddFriend";

import Transfer from "@/components/transfer/Transfer.vue";
import TransferResult from "@/components//transfer/TransferResult.vue";
import TransferFail from "@/components//transfer/TransferFail.vue";
import TransferPeding from "@/components//transfer/TransferPeding.vue";
import TransferSuccess from "@/components//transfer/TransferSuccess.vue";

import FriendInfo from "@/components/contacts/FriendInfo.vue"
import editGroupName from "@/components/contacts/editGroupName.vue"
import groupQrCode from "@/components/contacts/groupQrCode.vue"
import editGroupNickname from "@/components/contacts/editGroupNickname.vue"
const getTime = () => {
    return new Date().getTime();
};

export default {
    name: "app",
    components: {
        OnlineStatus,
        Socket,
        ChatRecord,

        Group,
        FriendAdd,
        AddFriend,

        Transfer,
        TransferResult,
        TransferFail,
        TransferPeding,
        TransferSuccess,


        FriendInfo,
        editGroupName,
        groupQrCode,
        editGroupNickname
    },
    data() {
        return {
            // noSimpleTips: '群已开启禁言，无法发送消息',
            noSimpleTips: this.$t('msg.已开启禁言'),

            isBottom: true,

            contacts: [],

            // 搜索联系人
            keywords: "",
            searchResult: false,
            // 搜索结果列表
            searchList: [],


            is_group: 0,//是否是群聊  0:好友  1:群聊
            group_id: '',//群聊ID

            im_id: '',//联系人ID

            // 创建群聊或者添加群员
            isAdd: 1,
            userIds: [],
            createChatBox: false,//创建群聊或者添加群员的开关
            friendAddBox: false,//添加好友搜索的开关
            addFriendBox: false,//发送申请的开关
            member: {},//传参


            groupUserCount: 0, //群聊人数
            group_name: "",  //群聊名称
            groupUserName: "",  //我在群聊中的名称
            isGroupAdmin: false,//是否是群主

            isTempMsg: false,//是否是临时会话
            rightShow: false,//是否展示右侧

            searchGroupUserName: "",//群成员检索字段
            groupAllUser: [],  //群成员所有人
            groupUserList: [],//群成员渲染到页面的

            is_expand: false, //群成员是否展开
            show_max_count: 18,//群成员未展开时显示的人数
            friendIds: [],//所有好友的ID集合，用于判断是否是好友

            popover_show: false,//好友信息展示 控制开关
            friend_popover: false,//群友信息展示 控制开关

            messageBox: false,//聊天记录弹窗开关
            currentChat: {},// 当前聊天的用户信息
            ChatRecordMap: {},//聊天记录弹窗参数


            dialogTitle: this.$t('navbar.createGroup'), //弹窗titla
            dialogBoolen: false, //是否显示弹窗
            dialogName: "", //控制弹窗 组件的显示
            transfer_id: null,

            all_kehu: [],//客服ID
            remark_friends: {},//好友备注映射


            componentKey: 1,//通过改变 改变组件，防止组件页面数据无变化

            // isFullscreen: false,

            unread: 0,
            curFile: null,

            newChatUser: null,//从好友列表或者群聊 点发消息 传过来的


            allUser: [],//所有用户



            // 当前登录用户
            user: {},

            params: {
                page: 1,
                limit: 10,
            },
            timer: null,

            // 当前消息
            currentMessage: {},
            // 最近联系人
            lastMessages: [],
            // 置顶列表
            playAudio: null,

            // 定义联系人的右键菜单
            contactContextmenu: [{
                icon: "el-icon-delete",
                color: "red",
                text: this.$t('msg.删除该聊天'),
                visible: instance => {
                    return instance.contact.is_group == 0;
                },
                click: (e, instance, hide) => {
                    hide();
                    const { IMUI, contact } = instance;
                    let del_id = contact.id,
                        is_group = contact.is_group;

                    this.$confirm(this.$t('msg.确定删除该聊天吗'), this.$t('msg.提示'), {
                        confirmButtonText: this.$t('msg.确定'),
                        cancelButtonText: this.$t('msg.取消'),
                        type: 'warning'
                    }).then(async () => {
                        this.$api.imApi.delChatAPI({
                            is_group: is_group,
                            id: del_id
                        }).then(res => {
                            if (res.code != 0) return;
                            this.$message({
                                type: "success",
                                message: this.$t('msg.删除成功'),
                            });
                            this.getSimpleChat();
                        })
                    }).catch(() => { });
                },
            }, {
                icon: "el-icon-delete",
                color: "red",
                text: this.$t('msg.清除群聊天'),
                visible: instance => {
                    return (
                        instance.contact.owner_id == this.user.id && instance.contact.is_group == 1
                    );
                },
                click: (e, instance, hide) => {
                    hide();
                    const { IMUI, contact } = instance;
                    let del_id = contact.id;

                    this.$confirm(this.$t('msg.确定清除群聊天记录吗'), this.$t('msg.提示'), {
                        confirmButtonText: this.$t('msg.确定'),
                        cancelButtonText: this.$t('msg.取消'),
                        type: 'warning'
                    }).then(async () => {
                        this.$api.imApi.clearMessageAPI({
                            id: del_id
                        }).then(res => {
                            if (res.code != 0) return;
                            this.$message({
                                type: "success",
                                message: this.$t('msg.清除成功'),
                            });
                            this.getSimpleChat();
                        })
                    }).catch(() => { });
                },
            }],
            contextmenu: [{
                text: this.$t('msg.删除该消息'),
                color: "red",
                // visible: instance => {
                //     return instance.message.fromUser.id == this.user.id && instance.message.is_group < 2 && this.globalConfig.chatInfo.dbDelMsg;
                // },
                click: (e, instance, hide) => {
                    hide();
                    const { IMUI, message } = instance;
                    this.$confirm(this.$t('msg.确认删除该消息吗'), this.$t('msg.提示'), {
                        confirmButtonText: this.$t('msg.确定'),
                        cancelButtonText: this.$t('msg.取消'),
                        type: 'warning'
                    }).then(() => {
                        this.$api.imApi.delMessageAPI({ id: message.id }).then(res => {
                            if (res.code != 0) return;
                            this.$message({
                                type: "success",
                                message: this.$t('msg.删除成功'),
                            });

                            const im_id = this.user_mmm.im_user_id;//当前用户的im_id

                            const is_group = message.is_group; //是否是群聊
                            const fromUserId = message.fromUser.id;//发送消息的用户id
                            const toContactId = message.toContactId;//接收消息的id


                            let contactId = toContactId;
                            if (is_group == 0) {
                                contactId = fromUserId == im_id ? toContactId : fromUserId;
                            }
                            const data = IMUI.getMessages(contactId);
                            const index = data.findIndex(item => item.id == message.id);
                            index > -1 ? data.splice(index, 1) : "";
                            IMUI.updateMessage(data);
                        })
                    }).catch(() => { });
                }
            }],
            // 群成员右键菜单
            groupMenu: [{
                text: this.$t('msg.发送消息'),
                click: (e, instance, hide) => {
                    const { IMUI, contact } = instance;
                    IMUI.changeContact(contact.user_id);
                    hide();
                },
                visible: instance => {
                    return instance.contact.user_id != this.user.id && this.globalConfig.sysInfo.runMode == 1;
                }
            },
            {
                text: this.$t('msg.查看资料'),
                click: (e, instance, hide) => {
                    const { IMUI, contact } = instance;
                    hide();
                    this.$user(contact.user_id);
                },
                visible: instance => {
                    // 不是自己才可以查看资料
                    return (
                        instance.contact.user_id != this.user.id
                    );
                }
            },
            {
                text: this.$t('msg.移出群聊'),
                color: "red",
                click: (e, instance, hide) => {
                    hide();
                    const { IMUI, contact } = instance;
                    this.$confirm(this.$t('msg.确定要移除该成员吗'), this.$t('msg.提示'), {
                        confirmButtonText: this.$t('msg.确定'),
                        cancelButtonText: this.$t('msg.取消'),
                        type: 'warning'
                    }).then(() => {
                        this.$api.imApi.removeUserAPI({ id: this.group_id, user_id: contact.user_id });
                    }).catch(() => { });
                },
                visible: instance => {
                    return (
                        instance.contact.user_id != this.user.id &&
                        this.currentChat.owner_id != instance.contact.user_id &&
                        this.currentChat.role <= 2
                    );
                }
            }],
            tools: [
                {
                    name: "msgBox",
                    title: this.$t('msg.历史消息'),
                    click: () => {
                        this.ChatRecordMap = {};
                        this.messageBox = true;
                        // 组件重置
                        this.componentKey += 1;
                    },
                    render: () => { return <i class="el-icon el-icon-time f-22" style="vertical-align: middle;"></i> },
                    isRight: true
                },
                {
                    name: "emoji",
                    title: this.$t('chat.发送表情'),
                    render: () => {
                        return <img src={require('@/assets/image/i1.png')} style="vertical-align: middle;width:46px;height:46px" />
                    }
                },
                {
                    name: "uploadImage",
                    title: this.$t('chat.发送图片'),
                    render: () => {
                        return <img src={require('@/assets/image/i2.png')} style="vertical-align: middle;width:46px;height:46px" />
                    }
                },
                {
                    name: "uploadVideo",
                    title: this.$t('chat.发送视频'),
                    click: () => {
                        var uploadVideo = this.$refs.uploadVideo;
                        uploadVideo.click();
                    },
                    render: () => {
                        return <div style="position:relative">
                            <img src={require('@/assets/image/i3.png')} style="vertical-align: middle;width:46px;height:46px" />
                            <input style="display:none" type="file" accept="video/*" ref="uploadVideo" on-change={e => {
                                this.uploadVideo(e);
                            }} />
                        </div>
                    }
                },
                {
                    name: "uploadFile",
                    title: this.$t('chat.发送文件'),
                    render: () => {
                        return <img src={require('@/assets/image/i4.png')} style="vertical-align: middle;width:46px;height:46px" />
                    }
                }
            ],
            transferTools: {
                name: "transfer",
                title: this.$t('msg.transfer'),
                click: () => {
                    let is_group = this.currentChat.is_group || 0;
                    if (is_group) return;
                    this.dialogTitle = this.$t('msg.transfer');
                    this.dialogName = "transfer";
                    this.dialogBoolen = true;
                },
                render: () => {
                    return <img src={require('@/assets/image/i5.png')} style="vertical-align: middle;width:46px;height:46px" />
                }
            }
        };
    },
    computed: {
        // 监听全局socket消息状态
        ...mapState({
            wsStatus: state => state.wsStatus, //ws是否在线
            socketAction: state => state.socketAction, //ws推送监听

            allContacts: state => state.allContacts,

            contactId: state => state.toContactId,
            contactSync: state => state.contactSync,

            user_mmm: state => state.user,
            setting: state => state.setting,

            userInfo: state => state.userInfo,
            globalConfig: state => state.globalConfig,
        }),
        formatTime() {
            return function (val) {
                return utils.timeFormat(val);
            };
        },
    },
    watch: {
        // 监听联系人搜索
        keywords() {
            const { IMUI } = this.$refs;
            const contacts = IMUI.getContacts();
            this.searchContact(contacts);
        },
        playAudio(val) {
            if (val && this.currentMessage) {
                let message = this.currentMessage;
                var that = this;
                const { IMUI } = this.$refs;
                this.playAudio.addEventListener('ended', function () {
                    that.playAudio = null;
                    that.currentMessage = null;
                    IMUI.updateMessage({
                        id: message.id,
                        status: 'successd',
                        isPlay: 0,
                    })
                }, false);
            }
        },
        // 监听接收socket消息
        async socketAction(val) {
            console.log(val)
            let message = val.data;
            const { IMUI } = this.$refs;
            let client_id = Lockr.get('client_id');
            switch (val.type) {
                //上线、下线通知
                case "isOnline":
                    IMUI.updateContact({
                        id: message.id,
                        is_online: message.is_online
                    })

                    break;
                case "offline":
                    // 如果开启了多设备同时登录，则不走后面的逻辑
                    if (parseInt(this.globalConfig.sysInfo.multipleLogin) == 1) {
                        return;
                    }
                    if (message.id == this.user.id && message.client_id != client_id && !message.isMobile) {
                        this.$message.error(this.$t('msg.其他地方登录'));
                        await new Promise(resolve => setTimeout(resolve, 1500))
                        this.$store.dispatch("LogOut").then(() => {
                            this.$router.push({ path: "/login" });
                        });
                    }
                    break;
                // 接收消息
                case "simple":
                case "group":
                    // 如果是自己发送的消息则不需要提示
                    if (message.fromUser.id != this.user.id) {
                        let contact = this.getContact(message.toContactId, message);
                        // 如果不是当前聊天对象，并且被@到，就要@的未读数量  
                        if (message.is_group == 1 && message.toContactId != this.currentChat.id) {
                            let at = 0;
                            // 如果at参数包含了我自己，就要增加@的数量
                            if (message.at.includes(this.user.id)) {
                                at = 1;
                            }
                            this.$refs.IMUI.updateContact({
                                id: message.toContactId,
                                is_at: contact.is_at + at
                            });
                        }
                    }
                    this.recieveMsg(message);
                    break;

                case "delMessage":
                    const im_id = this.user_mmm.im_user_id;
                    if (im_id == message.del_user) return;
                    const is_group = message.is_group;
                    if (is_group == 1) {
                        IMUI.removeMessage(message.id);
                        this._throttledGetSimpleChat && this._throttledGetSimpleChat();
                    }
                    if (is_group == 0) {
                        let contactId = message.to_user;
                        if (message.to_user == im_id) {
                            contactId = message.from_user;
                        }
                        const data = IMUI.getMessages(contactId);
                        const index = data.findIndex(item => item.id == message.id);
                        index > -1 ? data.splice(index, 1) : "";
                        IMUI.updateMessage(data);
                    }
                    break;
                case "updateMessage":
                    IMUI.updateMessage(message);
                    break;
                case "editGroupName":
                    IMUI.updateContact({
                        id: message.id,
                        displayName: message.displayName
                    });
                    break;
                //处理消息已读,将本地的未读消息修改为已读状态
                case "isRead":
                    this.setLocalMsgIsRead(message);
                    break;
                //某个人阅读了所有消息
                case "readAll":
                    let messages = IMUI.getMessages(message.toContactId);
                    messages.forEach(item => {
                        if (item.is_read == 0) {
                            const data = {
                                id: item.id,
                                is_read: 1,
                                status: "succeed",
                                sendTime: parseInt(item.sendTime) + 1,
                                content: item.content
                            };
                            IMUI.updateMessage(data);
                        }
                    });
                    break;
                // 新增加了群聊
                case "addGroup":
                    if (message.owner_id != this.user.id) {
                        IMUI.appendContact(message);
                    }
                    this.$api.commonApi.bindGroupAPI({ client_id: client_id, group_id: message.id });
                    break;
                // 设置群管理员
                case "setManager":
                case "addGroupUser":
                case "removeUser":
                    if (message.group_id == this.group_id && message.user_id != this.user.id) {
                        this.getGroupUserList(message.group_id);
                    }
                    // 如果移除人员是本人则删除联系人
                    if (val.type == 'removeUser' && message.user_id == this.user.id) {
                        // this.removeContact(message.group_id);
                    } else {
                        IMUI.updateContact({
                            id: message.group_id,
                            avatar: message.avatar
                        });
                    }
                    break;
                case "removeGroup":
                    this.removeContact(message.group_id);
                    break;
                // 清空群聊消息
                case "clearMessage":
                    IMUI.clearMessages(message.group_id);
                    IMUI.updateContact({
                        id: message.group_id,
                        lastContent: '',
                    })
                    if (message.group_id == this.currentChat.id) {
                        IMUI.changeContact(null);
                        // 清空后重新切换到群聊
                        setTimeout(() => IMUI.changeContact(message.group_id), 100)
                    }
                    break;
                // 更新配置
                case "updateConfig":
                    this.$store.commit('setGlobalConfig', message);
                    break;

                // 群聊设置
                case "groupSetting":
                    IMUI.updateContact({
                        id: message.group_id,
                        setting: message.setting
                    });
                    if (this.currentChat.id == message.group_id) {
                        this.currentChat.setting = message.setting;
                    }
                    break;
                case 'appendContact':
                    IMUI.appendContact(message);
                    break;
                case 'webrtc':
                    break;
            }
        }
    },

    async beforeCreate() {
        let { userinfo } = await this.$api.usersApi.userIndex();
        this.all_kehu = userinfo.all_kehu;
        this.remark_friends = userinfo.remark_friends;
    },
    created() {
        let userInfo = this.userInfo;
        this.user = {
            id: userInfo.user_id,
            displayName: userInfo.realname,
            avatar: userInfo.avatar,
            account: userInfo.account
        }
        // 初始化 getSimpleChat 的节流函数，2 秒内最多触发一次
        this._throttledGetSimpleChat = this._throttle(this.getSimpleChat, 2000);
    },
    mounted() {
        // 初始化联系人
        this.getSimpleChat();
        this.getFriendAll();
        let newChatUser = this.newChatUser = this.$store.state.newChatUser;
        if (newChatUser) this.createTempMsg()
    },
    destroyed() {
        clearTimeout(this.timer);
    },
    methods: {
        // 通用节流函数
        _throttle(func, wait) {
            let lastInvokeTime = 0;
            let timeoutId = null;
            const context = this;
            return function throttled(...args) {
                const now = Date.now();
                const remaining = wait - (now - lastInvokeTime);
                if (remaining <= 0) {
                    if (timeoutId) {
                        clearTimeout(timeoutId);
                        timeoutId = null;
                    }
                    lastInvokeTime = now;
                    return func.apply(context, args);
                }
                if (!timeoutId) {
                    timeoutId = setTimeout(() => {
                        lastInvokeTime = Date.now();
                        timeoutId = null;
                        func.apply(context, args);
                    }, remaining);
                }
            };
        },
        // 重新链接ws
        reconnect() {
            this.$refs.socket.initWebSocket();
        },
        // 搜索联系人
        searchContact(contacts) {
            if (this.keywords == "") return;
            this.searchList = utils.search_object(
                contacts,
                ["displayName", "name_py"],
                this.keywords
            );
        },
        // 关闭搜索结果
        closeSearch() {
            setTimeout(() => this.searchResult = false, 300);
        },

        // 创建群聊或者添加好友
        handleCommand(e) {
            if (e == 'addGroup') this.openCreateGroup();
            if (e == 'addFriend') this.friendAddBox = true;
        },
        add_send_msg(contact) {
            this.newChatUser = contact;
            this.createTempMsg();
        },
        // 打开创建团队的窗口
        openCreateGroup() {
            this.isAdd = 1;
            this.dialogTitle = this.$t('msg.发起群聊');
            this.userIds = [];
            this.createChatBox = true;
        },

        // 打开添加群成员的窗口
        openAddGroupUser() {
            let user_ids = utils.arrayToString(this.groupUser, "user_id");
            this.isAdd = 0;
            this.userIds = user_ids;
            this.dialogTitle = this.$t('msg.添加群成员');
            this.createChatBox = true;
        },
        // 添加群成员或者创建群聊
        manageGroup(selectUid, isAdd, groupName) {
            this.createChatBox = false;
            let num = this.globalConfig.chatInfo.groupUserMax;
            if (isAdd == 0) {
                if ((selectUid.length + this.groupUser.length) > num && num > 0) {
                    return this.$message.error(this.$t('msg.群成员不能大于') + num + this.$t('my.人'));
                }
                this.$api.imApi.addGroupUserAPI({ user_ids: selectUid, id: this.group_id });
            } else if (isAdd == 1) {
                if (selectUid.length > num && num > 0) {
                    return this.$message.error(this.$t('msg.群成员不能大于') + num + this.$t('my.人'));
                }
                // , name: groupName
                this.$api.imApi.addGroupAPI({ user_ids: selectUid }).then(res => {
                    const data = res.data;
                    const { IMUI } = this.$refs;
                    if (res.code == 0) {
                        // 添加联系人
                        IMUI.appendContact(data);
                        // 切换到该联系人
                        IMUI.changeContact(data.id);
                    }
                });
            }
        },

        // 群内搜索群员
        searchGroupUser() {
            let key = this.searchGroupUserName;
            this.groupUserList = this.groupAllUser.filter(item => item.userInfo.displayName.includes(key))
        },
        // 查看更多群员
        showMoreGroupUsers() {
            if (this.is_expand) {
                this.is_expand = false;
                let show_max_count = this.show_max_count;
                this.userList = this.groupAllUser.slice(0, show_max_count);
            } else {
                this.is_expand = true;
                this.userList = this.groupAllUser;
            }
        },


        // 查看个人资料
        async lookData(item) {
            this.im_id = item.user_id;
            this.friend_popover = true;
            // this.$user(item.user_id);
        },
        // 添加好友
        async add_friend(item) {
            let friendIds = this.friendIds;
            let user_id = item.user_id;
            if (friendIds.includes(user_id)) {
                this.$message({
                    message: this.$t('msg.已经是好友'),
                    type: 'warning'
                });
            } else {
                this.member = item;
                this.addFriendBox = true;
            }
        },
        // 发送消息
        send_msg(item) {
            item.id = item.user_id;
            item.displayName = item.userInfo.displayName;
            item.avatar = item.userInfo.avatar;
            this.newChatUser = item;
            this.createTempMsg();
        },

        // 修改群聊名称和个人群聊名称的弹窗
        changeGroupName(title) {
            if (title == 'editGroupName') {
                if (!this.isGroupAdmin) {
                    this.$message({
                        message: this.$t('msg.无权操作'),
                        type: 'error'
                    });
                    return
                };
                this.dialogTitle = this.$t("msg.群聊名称");
            }

            if (title == 'groupQrCode') {
                this.dialogTitle = this.$t("msg.群聊");
            }
            if (title == 'editGroupNickname') {
                this.dialogTitle = this.$t("msg.我在群里昵称");
            }
            this.dialogName = title;
            this.dialogBoolen = true;
        },
        // 弹窗修改后的回调
        changeCallback(res) {
            if (res.type == 'group') {
                this.group_name = res.name;
            }
            if (res.type == 'user') {
                this.groupUserName = res.name;
                this.getGroupUserList(this.group_id)
            }
            this.dialogBoolen = false;
        },

        // 清除群聊天记录
        clearGroupMsg() {
            if (!this.isGroupAdmin) {
                this.$message({
                    message: this.$t('msg.无权操作'),
                    type: 'error'
                });
                return
            };

            this.$confirm(this.$t('msg.确定清空聊天记录吗'), this.$t('msg.提示'), {
                confirmButtonText: this.$t('live.确定'),
                cancelButtonText: this.$t('chat.取消'),
                type: "warning"
            }).then(() => {
                this.$api.imApi.clearMessageAPI({
                    id: id
                }).then((res) => {
                    this.$message({
                        type: "success",
                        message: this.$t('msg.清空成功')
                    });
                })
            }).catch(() => { });
        },
        // 退出群聊
        removeUser() {
            this.$confirm(this.$t('msg.确定退出群聊吗'), this.$t('msg.提示'), {
                confirmButtonText: this.$t('live.确定'),
                cancelButtonText: this.$t('chat.取消'),
                type: "warning"
            }).then(() => {
                let group_id = this.currentChat.id;
                this.$api.imApi.removeUserAPI({ id: group_id, user_id: this.user.id }).then(res => {
                    if (res.code != 0) return;
                    this.$message({
                        type: "success",
                        message: this.$t('msg.退出成功')
                    });
                    this.removeContact(group_id);
                });
            }).catch(() => { });
        },
        // 解散群聊
        removeGroup() {
            if (!this.isGroupAdmin) {
                this.$message({
                    message: this.$t('msg.无权操作'),
                    type: 'error'
                });
                return
            };
            this.$confirm(this.$t('msg.确定解散群聊吗'), this.$t('msg.提示'), {
                confirmButtonText: this.$t('live.确定'),
                cancelButtonText: this.$t('chat.取消'),
                type: "warning"
            }).then(() => {
                let group_id = this.currentChat.id;
                this.$api.imApi.removeGrouprAPI({ id: group_id }).then(res => {
                    if (res.code != 0) return;
                    this.$message({
                        type: "success",
                        message: this.$t('msg.解散成功')
                    });
                    this.removeContact(group_id);
                })
            }).catch(() => { });
        },

        closeFriendInfo() {
            this.popover_show = this.rightShow = false;
        },

        // 设置发送键
        setSendKey(e) {
            return this.setting.sendKey == 1 ? (e.keyCode == 13 && !e.ctrlKey && !e.shiftKey) : (e.keyCode == 13 && e.ctrlKey);
        },
        // 输入框换行检查函数
        wrapKey(e) {
            return this.setting.sendKey == 1 ? (e.keyCode == 13 && e.ctrlKey) : (e.keyCode == 13 && !e.ctrlKey && !e.shiftKey);
        },
        // 初始化最近联系人
        latelyContacts(contacts) {



            const data = contacts.filter(item => item.lastContent && item.id != -1 && item
                .is_public != 1);


            data.sort((a, b) => b.lastSendTime - a.lastSendTime);
            const all_kehu = this.all_kehu;
            const remark_friends = this.remark_friends;

            data.forEach(item => {
                if (remark_friends[item.user_id]) {
                    item.displayName = remark_friends[item.user_id];
                }
            })
            data.sort((a, b) => {
                const aInKehu = all_kehu.includes(a.id);
                const bInKehu = all_kehu.includes(b.id);
                if (aInKehu && !bInKehu) return -1;
                if (!aInKehu && bInKehu) return 1;
                return 0;
            });
            return data;
        },
        eventBottom(isBottom) {
            this.isBottom = isBottom;
        },
        // 切换聊天窗口时要检测那些消息未读
        handleChangeContact(contact, instance) {
            const { IMUI } = this.$refs;
            this.isTempMsg = false;
            this.rightShow = false;

            let tools = this.tools;
            let index = tools.findIndex(item => item.name == 'transfer');
            if (contact.is_group == 0) {
                if (index < 0) tools.push(this.transferTools);
            } else {
                if (index >= 0) tools.splice(index, 1);
            }

            if (contact.is_group != 1) this.getUserInfo(contact.id);
            // 初始化工具栏
            IMUI.initEditorTools(tools);
            instance.updateContact({
                id: contact.id,
                unread: 0
            });
            // 将未读的总数减去当前选择的聊天
            if (contact.is_notice == 1) {
                this.unread -= contact.unread;
            }
            // 聊天记录列表恢复到最初第一页
            this.params.page = 1;
            // this.displayName = contact.displayName;
            // this.oldName = contact.displayName;
            this.currentChat = contact;
            console.log("切换contact", contact)
            // 如果是群聊，获取群成员列表
            if (contact.is_group == 1) {
                this.group_name = contact.displayName;
                this.isGroupAdmin = contact.owner_id == this.user.id;//判断是否是群主
                // 如果刚才拉取过，并且没有切换过群聊，现在就不用拉取了，直接设置@的成员列表
                if (this.group_id != contact.id) {
                    this.getGroupUserList(contact.id);
                }
            }
            //切换聊天后全局设置是否是群聊或者单聊
            this.is_group = contact.is_group || 0;
            // 如果是团队id，保存当前团队id避免下次切换回来的时候重复请求成员列表
            if (this.is_group == 1) {
                this.group_id = contact.id;
                this.notice = contact.notice;
            }
            var data = [];
            // 获取当前聊天窗口的所有消息
            var messages = IMUI.getMessages(contact.id);
            for (var i = 0; messages.length > i; i++) {
                if (
                    messages[i].is_read == 0 &&
                    messages[i].fromUser.id != this.user.id
                ) {
                    messages[i]['contactInfo'] = {};
                    data.push(messages[i]);
                }
            }
            // 如果有未读的消息，需要将消息修改为已读
            if (data.length > 0) {
                let is_group = contact.is_group || 0;
                this.$api.imApi.setMsgIsReadAPI({
                    is_group: is_group,
                    toContactId: contact.id,
                    messages: data,
                    fromUser: contact.id
                })
                this.setLocalMsgIsRead(data);
            }
            instance.closeDrawer();
        },

        // 将本地消息设置为已读
        setLocalMsgIsRead(message) {
            const { IMUI } = this.$refs;
            for (let i = 0; message.length > i; i++) {
                const data = {
                    id: message[i]["id"],
                    is_read: 1,
                    status: "succeed",
                    sendTime: parseInt(message[i]["sendTime"]) + 1,
                    content: message[i]["content"]
                };
                IMUI.updateMessage(data);
            }
        },

        // 拉取聊天记录
        handlePullMessages(contact, next, instance) {
            let params = this.params;
            // 获取当前聊天的最上面一条消息，并将id传入后端获取比改id要小的消息，page永远设置为1.
            let message = instance.getMessages(contact.id);
            if (message.length > 0) {
                params.last_id = message[0].msg_id;
                params.page = 1;
            } else {
                params.last_id = 0;
            }
            params.toContactId = contact.id;
            params.is_group = contact.is_group || 0;
            this.$api.imApi.getMessageListAPI(params).then(res => {
                this.params.page++;
                let isEnd = false;
                let messages = res.data;
                if (messages.length < this.params.limit) {
                    isEnd = true;
                }
                next(messages, isEnd);
            }).catch(error => {
                next([], true);
            });
            return true;
        },

        // 点击了聊天消息消息
        handleMessageClick(e, key, message, instance) {
            if (key == 'avatar') {
                if (message.is_group == 1 && this.currentChat.setting.profile == 0 && this.currentChat.role > 2) {
                    this.$message.error(this.$t('msg.已开启隐私'));
                    return;
                }
                if (message.fromUser.id == this.user.id) {
                    return;
                }
                this.$user(message.fromUser.id);
                return;
            }
            if (message.type == 'transfer') {
                this.transfer_id = message.transfer_id;
                if (message.fromUser.id == this.user.id) {
                    // 自己发的
                    if (message.transfer_status == 1) {
                        this.dialogTitle = this.$t("msg.支付成功");
                        this.dialogName = "result";
                    } else {
                        this.dialogTitle = this.$t("chat.已被退还");
                        this.dialogName = "fail";
                    }
                } else {
                    // 别人发的
                    if (message.transfer_status == 1) {
                        this.dialogTitle = this.$t("navbar.pending");
                        this.dialogName = "peding";
                    } else {
                        this.dialogTitle = this.$t("chat.已收款");
                        this.dialogName = "success";
                    }
                }
                this.dialogBoolen = true;
            }
            if (message.type == 'webrtc') {
                this.$message.error(this.$t("msg.使用移动端进行通话"));
            }

            // 语音消息点击事件
            if (message.type == 'voice') {
                // 如果没有其他语音在播放，直接播放
                if (!this.playAudio) {
                    this.currentMessage = message;
                    return this.playVoice(message, instance);
                }
                //只要有在播放的直接停止
                this.playAudio.pause();
                this.playAudio = null;
                instance.updateMessage({
                    id: this.currentMessage.id,
                    status: "successd",
                    isPlay: 0,
                })
                // 如果不是点击的同一条数据，重新进行播放
                if (message.id != this.currentMessage.id) {
                    this.currentMessage = message;
                    this.playVoice(message, instance);
                }
            }
            var imageTypes = ["image", "file", "video"];
            if (imageTypes.includes(message.type)) {
                if (!message.preview) {
                    return this.$message.error(this.$t("msg.没有配置预览接口"));
                }
                this.$preview(message.preview);
            }
        },
        playVoice(message, instance) {
            this.playAudio = new Audio(message.content);
            this.playAudio.play(); //播放这个音频对象
            instance.updateMessage({
                id: message.id,
                status: "succeed",
                isPlay: 1,
            })
        },

        // 发送聊天消息
        handleSend(message, next, file) {
            const { IMUI } = this.$refs;
            message.is_group = this.is_group;
            this.curFile = file;
            // 如果开启了群聊禁言或者关闭了单聊权限，就不允许发送消息
            if (!this.nospeak()) {
                IMUI.removeMessage(message.id);
                this.$message.error(this.noSimpleTips);
                return false;
            }
            let formdata = new FormData();
            // 如果是文件选择文件上传接口
            if (file) {
                // 判断文件如果大于5M就删除该聊天消息
                if (file.size > (this.globalConfig.fileUpload.size * 1024 * 1024)) {
                    IMUI.removeMessage(message.id);
                    // this.$t("msg.没有配置预览接口")

                    return this.$message.error(this.$t("msg.上传的内容不等大于") + this.globalConfig.fileUpload.size + "MB！");
                }
                formdata.append("file", file);
                formdata.append("message", JSON.stringify(message));
                this.$api.imApi.sendFileAPI(formdata).then(res => {
                    if (res.code == 0) {
                        IMUI.setEditorValue("");
                        IMUI.updateMessage(res.data);
                        next();
                    } else {
                        next({ status: "failed" });
                    }
                }).catch(error => {
                    next({ status: "failed" });
                });
            } else {
                this.$api.imApi.sendMessageAPI(message).then(res => {
                    if (res.code == 0) {
                        IMUI.setEditorValue("");
                        IMUI.updateMessage(res.data);
                        next();
                    } else {
                        next({ status: "failed" });
                    }
                }).catch(error => {
                    next({ status: "failed" });
                });
            }
        },

        // 开临时聊天
        createTempMsg() {
            const { IMUI } = this.$refs;
            let data = this.newChatUser;
            let contact = IMUI.findContact(data.id);

            if (!contact) {
                IMUI.appendContact(data);
                setTimeout(() => IMUI.changeContact(data.id), 10);
            } else {
                IMUI.changeContact(data.id);
            }
            this.$store.commit('changeChatUser', null);
        },

        // 获取所有好友,用于判断群内人员是否是好友
        async getFriendAll() {
            let { list: res } = await this.$api.chatApi.friendAllList({
                keyword: ""
            });
            let arr = [];
            res.forEach(item => arr.push(item.friend_user_info.im_user_id));
            this.friendIds = arr;
        },
        // 初始化聊天
        getSimpleChat(update) {
            // clearTimeout(this.timer);
            // this.timer = setTimeout(() => this.getSimpleChat(), 5 * 1000);
            this.$nextTick(() => {
                const IMUI = this.$refs.IMUI;
                this.IMUI = IMUI;
                IMUI.setLastContentRender("voice", message => {
                    return `[${this.$t('msg.语音')}]`;
                });
                IMUI.setLastContentRender("video", message => {
                    return `[${this.$t('msg.视频')}]`;
                });
                IMUI.setLastContentRender("webrtc", message => {
                    return `[${this.$t('msg.音视频通话')}]`;
                });
                IMUI.setLastContentRender("transfer", message => {
                    return `[${this.$t('msg.转账')}]`;
                });

                // 初始化表情
                IMUI.initEmoji(EmojiData);

                // 获取联系人列表
                this.$api.imApi.getContactsAPI().then(res => {
                    const data = res.data;
                    this.contacts = data;
                    const liveGroup = data.filter(item => item.is_group == 1 && item.is_public == 1);
                    const im_id = this.user_mmm.im_user_id;
                    liveGroup.forEach(item => {
                        if (item.owner_id == im_id) {
                            this.$api.imApi.removeGrouprAPI({ id: item.id })
                        } else {
                            this.$api.imApi.removeUserAPI({ id: item.id, user_id: im_id })
                        }
                    });
                    var msg = {};
                    // 重新渲染消息
                    data.forEach((item, index) => {
                        if (item.type) {
                            msg.type = item.type;
                            msg.content = item.lastContent;
                            data[index]['lastContent'] = IMUI.lastContentRender(msg);
                        }
                        if (item.unread && !update && item.is_notice == 1) {
                            this.unread += item.unread;
                        }
                    })
                    this.$store.commit('initContacts', data);
                    IMUI.initContacts(data);
                    this.lastMessages = IMUI.lastMessages;
                });
            });
        },

        // 获取联系人
        getContact(id, message = null) {
            const { IMUI } = this.$refs;
            let contact = IMUI.findContact(id);
            // 如果没有该联系人，需要新增，相当于临时会话
            if (!contact && message && message.contactInfo) {
                contact = message.contactInfo;
                IMUI.appendContact(contact);
            }
            return contact;
        },

        // 打开聊天窗口
        openChat(contactId, instance) {
            this.keywords = "";
            instance.changeContact(contactId);
        },

        // 获取用户个人信息,主要判断是否是好友
        async getUserInfo(im_id) {
            let res = await this.$api.chatApi.searchUser({
                im_user_id: im_id
            });
            let is_friend = res.user.is_friend;
            this.isTempMsg = is_friend ? false : true;
            return Promise.resolve(res)
        },

        // 发送视频
        uploadVideo(e) {
            // 如果开启了群聊禁言或者关闭了单聊权限，就不允许发送消息
            if (!this.nospeak()) {
                this.$message.error(this.noSimpleTips);
                return false;
            }
            let file = e.srcElement.files[0];
            let url = URL.createObjectURL(file);
            //经测试，发现audio也可获取视频的时长
            let audioElement = new Audio(url);
            let duration;
            audioElement.addEventListener("loadedmetadata", function (_event) {
                duration = audioElement.duration;
            });
            let message = {
                content: url,
                fromUser: this.user,
                id: utils.generateRandId(),
                sendTime: getTime(),
                status: 'going',
                toContactId: this.currentChat.id,
                type: 'video',
                extends: {
                    duration: duration
                }//录音时长
            }
            this.diySendMessage(message, file);
            // 将选择的文件清空
            this.$refs.uploadVideo.value = '';
        },
        // 把联系人删除 主要删除的是群聊
        removeContact(id) {
            const { IMUI } = this.$refs;
            const contact = IMUI.getCurrentContact();
            if (contact.id == id) {
                IMUI.changeContact(null);
            }
            IMUI.removeContact(id);
        },
        // 发送红包成功的回调
        transfer_ok(data) {
            let message = {
                id: utils.generateRandId(),
                type: 'transfer',
                sendTime: getTime(),
                extends: {},
                fromUser: this.user,
                is_group: 0,
                is_read: 0,
                toContactId: this.currentChat.id,
                status: 'going',
                ...data
            }
            this.diySendMessage(message);
            this.dialogBoolen = false;
        },
        // 红包领取或者退回后的回调函数
        peding_ok() {
            this.dialogBoolen = false;
        },
        //自定义消息的发送
        diySendMessage(message, file) {
            const { IMUI } = this.$refs;
            IMUI.appendMessage(message, true);
            this.handleSend(message, function () {
                var replaceMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
                    status: "succeed"
                };
                IMUI.updateContact({
                    id: message.toContactId,
                    lastContent: IMUI.lastContentRender(message),
                    lastSendTime: message.sendTime
                });
                IMUI.CacheDraft.remove(message.toContactId);
                IMUI.updateMessage(Object.assign(message, replaceMessage));
            }, file);
        },
        // 禁言时禁止发送消息
        nospeak() {
            if (this.is_group == 1 && this.currentChat.setting.nospeak > 0) {
                if (this.currentChat.setting.nospeak == 1 && this.currentChat.role < 3) {
                    return true;
                } else if (this.currentChat.setting.nospeak == 2 && this.currentChat.role == 1) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        },
        // 获取群聊成员列表
        getGroupUserList(group_id) {
            this.$api.imApi.groupUserListAPI({
                group_id: group_id
            }).then(res => {
                if (res.code != 0) return;
                let data = res.data;

                this.groupAllUser = JSON.parse(JSON.stringify(data));

                let show_max_count = this.show_max_count;
                this.groupUserList = data.slice(0, show_max_count);

                this.groupUserCount = data.length;

                let user = data.find(item => item.user_id == this.userInfo.user_id);
                this.groupUserName = user.nickname || user.userInfo.displayName;
            });
        },
        // 接收消息重新渲染
        recieveMsg(message) {
            const { IMUI } = this.$refs;
            const contact = IMUI.getCurrentContact();
            // 如果收到消息是当前窗口的聊天，需要将消息修改为已读
            if (contact.id == message.toContactId && contact.id != 'system') {
                var data = [];
                data.push(message);
                let is_group = contact.is_group || 0;
                this.$api.imApi.setMsgIsReadAPI({
                    toContactId: contact.id,
                    is_group: is_group,
                    messages: data,
                    fromUser: message.fromUser.id
                });
            } else {
                // 如果不是自己的消息，需要将未读数加1
                if (this.user.id != message.fromUser.id) {
                    let formContact = this.getContact(message.toContactId);
                    // 有消息提醒才会增加未读数
                    if (formContact.is_notice == 1) {
                        this.unread++;
                    }
                }
            }

            if (this.user.id == message.toContactId) {
                // 这里需要将原来的发送对象的id换回来，哈哈哈
                message.toContactId = message.toUser;
            }
            if (message.toContactId == 'system') {
                IMUI.updateContact({
                    id: message.toContactId,
                    lastContent: IMUI.lastContentRender(message),
                    lastSendTime: message.sendTime,
                    unread: '+1'
                });
            }
            IMUI.appendMessage(message, this.isBottom);
        },
    }
};
</script>
<style scoped lang="scss">
.recent_contact {
    flex: 1;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.main-container {
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    width: 100%;
    height: 100vh;
    background-size: cover;
}

.messageBoxStyle {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100%;
    z-index: 1999;
    background: rgba(0, 0, 0, 0.5);
    overflow-y: visible;

    .el-dialog__wrapper {
        display: flex;
        align-items: center;
    }
}


.contact_item {
    border-radius: 8px;
    padding: 18px 24px;
    box-sizing: border-box;
    overflow: hidden;
    display: flex;

    .contact_badge {
        position: relative;

        .contact_avatar {
            width: 54px;
            height: 54px;
            border-radius: 4px;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .is_online {
            position: absolute;
            bottom: -6px;
            right: -6px;
            border-radius: 50%;
            border: solid 3px #fff;
            height: 12px;
            width: 12px;
            background-color: limegreen;
        }
    }

    .contact_info {
        flex: 1;
        padding-left: 12px;
        box-sizing: border-box;

        overflow: hidden;

        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .contact_other {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .name {
                font-weight: 500;
                font-size: 18px;
                color: #333333;
                font-family: PingFang SC, PingFang SC;

                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .time {
                font-size: 14px;
                color: #9A9A9A;
            }
        }

        .last_msg {
            flex: 1;
            font-size: 14px;
            color: #7F7F7F;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .last_msg_view {
                // width: 300px;
                flex: 1;
                display: flex;
                align-content: center;
                overflow: hidden;

                padding-right: 10px;
                box-sizing: border-box;

                .last_msg_span {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            img {
                height: 14px;
                display: inline-block;
                vertical-align: middle;
                margin: 0 1px;
                position: relative;
                top: -1px;
            }
        }
    }
}

.cover {
    text-align: center;
    user-select: none;
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);

    i {
        font-size: 84px;
        color: #e6e6e6;
    }

    p {
        font-size: 18px;
        color: #ddd;
        line-height: 50px;
    }
}

.displayName {
    font-size: 16px;
    visibility: visible;
}

.contact-fixedtop-box {
    padding: 24px 40px;
    box-sizing: border-box;
    background: #FCFCFE;
    display: flex;
    align-items: center;
    justify-content: space-between;
    visibility: visible;
    position: relative;

    .input-with-select {
        ::v-deep input {
            height: 44px;
        }
    }
}

.dropdown_item {
    width: 116px;
    height: 32px;
    padding: 12px 0;
    border-radius: 0px 0px 0px 0px;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
        width: 20px;
        height: 20px;
    }

    span {
        font-size: 14px;
        color: #333333;
        margin-left: 8px;
    }
}

.search-list {
    background: #fff;
    position: absolute;
    z-index: 99;
    top: 70px;
    width: 326px;
    height: 300px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
    overflow: auto;
    border: solid 1px #e6e6e6;

    .search-list-item :hover {
        background: #f1f1f1;
    }

    .lemon-contact {
        background: #fff;
    }
}

.search-list-item ::v-deep .lemon-contact {
    padding: 10px
}

.chat-top-list {
    display: flex;
    padding: 0 5px 10px 10px;
    justify-content: flex-start;
    flex-wrap: wrap;
}



.message-title-box {
    // height: 92px;
    background: #FCFCFE;
    height: 26px;
    padding: 15px;

    display: flex;
    align-items: center;
    justify-content: space-between;
    visibility: visible;
    position: relative;

    .message_warning {
        width: 100%;
        height: 52px;
        background: #FFF7E8;
        // display: none;

        position: absolute;
        left: 0;
        bottom: -52px;
        z-index: 2;

        &_content {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;

            img {
                width: 24px;
                height: 24px;
            }

            span {
                font-size: 14px;
                color: #FF7D00;
                margin-left: 4px;
            }
        }

        &_close {
            cursor: pointer;
            position: absolute;
            right: 24px;
            top: 14px;
            z-index: 2;
        }
    }
}

.message-title-tools {
    font-size: 20px;
    color: #999999;
    letter-spacing: 5px;
    cursor: pointer;
}

.editInput {
    font-size: 18px;
    border: none;
    width: 400px;
}

.editInput:focus {
    outline: -webkit-focus-ring-color auto 0px;
}

.lemon-last-content {
    display: flex;
    justify-content: space-between;

    .lastContent {
        width: 150px !important;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
}

.slot-group-list {
    width: 280px;
    height: 100%;
    // border-left: solid 1px #e6e6e6;
    border-left: 1px solid #EDEDED;
    padding: 16px 24px 0;
    box-sizing: border-box;
    background: #fff;
    white-space: initial;

    .group_content {
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .group_user_list {
        overflow-y: auto;
        display: flex;
        flex-wrap: wrap;
        padding-top: 24px;

        :deep(.lemon-contact) {
            width: 25%;
            overflow: hidden;

            .group_user_item {
                width: 100%;
            }
        }

        :deep(.el-popover__reference-wrapper) {
            width: 100%;
            overflow: hidden;
        }

        .group_user_item {
            width: 25%;
            height: 72px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            overflow: hidden;

            &_info {
                width: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                overflow: hidden;
            }

            .group_user_avatar {
                width: 44px;
                height: 44px;
                border-radius: 4px 4px 4px 4px;
            }

            .group_user_name {
                width: 100%;
                font-size: 12px;
                color: #333333;
                padding: 4px 6px 8px;
                box-sizing: border-box;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
        }
    }

    .group_bottom {
        min-height: 280px;
    }

    .group_more {
        border-bottom: 1px solid #EDEDED;
        padding: 8px 0 24px;
        box-sizing: border-box;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;

        span {
            font-size: 14px;
            color: #000000;
        }

        img {
            width: 20px;
            height: 20px;
        }
    }

    .group_setup {
        border-bottom: 1px solid #EDEDED;
        padding: 16px 0;

        cursor: pointer;

        &_item {
            padding-bottom: 8px;

            &:last-child {
                padding-bottom: 0;
            }
        }

        &_key {
            font-size: 14px;
            color: #333333;
        }

        &_value {
            font-size: 14px;
            color: #7F7F7F;
            margin-top: 4px;
        }
    }

    .group_clear_msg {
        font-size: 14px;
        color: #333333;
        border-bottom: 1px solid #EDEDED;
        padding: 16px 0;

        cursor: pointer;
    }

    .group_out {
        text-align: center;
        font-size: 14px;
        color: #FF4C4C;
        border-bottom: 1px solid #EDEDED;
        padding: 16px 0;
        cursor: pointer;
    }

    .group_user {
        width: 100%;

        .group_user_info {
            width: 100%;
            border-bottom: 1px solid #EDEDED;
            padding-bottom: 22px;
            cursor: pointer;
            display: flex;

            .group_user_avatar {
                width: 44px;
                height: 44px;
                border-radius: 4px 4px 4px 4px;
            }

            .group_user_other {
                padding-left: 8px;
                box-sizing: border-box;

                .group_user_name {
                    font-size: 14px;
                    color: #333333;
                }

                .group_user_id {
                    font-size: 14px;
                    color: #7F7F7F;
                }
            }
        }

        .group_msg_item {
            width: 100%;
            height: 52px;
            font-size: 14px;
            color: #333333;
            border-bottom: 1px solid #EDEDED;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: default;

            img {
                width: 20px;
                height: 20px;
            }
        }
    }
}

.group-side-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: nowrap;
    justify-content: space-between;
}

.group-notice {
    height: 140px;
}

.group-user {
    min-height: 300px;
    overflow: auto;
}

.lemon-contact-item {
    padding: 10px;
}

.at-item {
    background-color: #fff;
    border-radius: 30px;
    color: #18bc37;
    padding: 6px 8px;
    border: solid 1px;
}

.el-badge ::v-deep .el-badge__content {
    background-color: #f5222d;
}

.message-quote {
    padding: 4px;
    font-size: 12px;
    background-color: #e3e3e3;
    border-radius: 4px;

    .text-overflow {
        overflow: hidden !important;
        text-overflow: ellipsis;
        white-space: nowrap !important;
        width: 200px;
    }
}
</style>
<!-- 兼容lemon样式 -->
<style lang="scss">
.lemon-menu {
    width: 162px;
    background: #F2F7FF;

    .lemon-avatar {
        width: 62px !important;
        height: 62px !important;
        margin: 34px 0 64px;
    }

    .lemon-menu__item--active {
        background: #FCFCFE;
    }
}

// 右侧
.lemon-container {
    background: #FFFFFF;

    .lemon-container__title {
        padding: 0;
    }

    .lemon-messages {
        background: #EDEDED;
    }
}

.lemon-sidebar {
    width: 456px !important;
    background: #FCFCFE;
    box-shadow: inset -1px 0px 0px 0px rgba(104, 104, 104, 0.1);

    .lemon-sidebar__scroll {
        padding: 0 15px;
        box-sizing: border-box;
        background: #FCFCFE;

        // .lemon-contact {
        //   border-radius: 8px;
        //   padding: 18px 24px;
        //   box-sizing: border-box;
        //   overflow: hidden;
        // }
    }
}


.lemon-editor__tool {
    border-top: solid 1px #e6e6e6;
}

.no-internet {
    background-color: #fef0f0;
    color: #f56c6c;
}

.lemon-contact {
    padding: 0;
    background: #FCFCFE;
}

.lemon-sidebar .lemon-contact--active {
    background: #D9E7FE;
}

.lemon-contact--active .bg-gray {
    background: #d9d9d9;
}

.bg-gray {
    background-color: #e7e7e7;
}

.lemon-wrapper--theme-blue .lemon-contact--active .bg-gray {
    background: #e7e7e7 !important;
}

.lemon-wrapper--theme-blue .bg-gray {
    background-color: #efefef !important;
}

.bage-gray {
    background-color: #ccc;
}

.lemon-editor__tip {
    flex: 1
}

.lemon-contact.lemon-contact--name-center {
    padding: 10px;
}


// 群组
.popover_content {
    width: 260px;
    padding: 12px;
    box-sizing: border-box;

    &_view {
        border-bottom: 1px solid #EDEDED;
        padding-bottom: 16px;
        display: flex;

        .popover_avatar {
            width: 52px;
            height: 52px;
            border-radius: 4px 4px 4px 4px;
        }

        .popover_info {
            padding: 5px 12px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .popover_name {
            font-size: 18px;
            color: #333333;
        }

        .popover_id {
            font-size: 12px;
            color: #7F7F7F;
        }
    }



    .popover_btn {
        padding-top: 32px;
        display: flex;
        justify-content: space-between;

        &_item {
            width: 113px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            font-size: 14px;
            color: #FFFFFF;
            background: #2273FF;
            border-radius: 8px 8px 8px 8px;
            border: 1px solid #2273FF;
            cursor: pointer;

            &:last-child {
                color: #2273FF;
                background: #FFFFFF;
            }
        }
    }
}

// 个人</style>